document.addEventListener('DOMContentLoaded', function() {
    const registerForm = document.getElementById('registerForm');
    
    registerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 注册前清空localStorage，防止老数据影响
        localStorage.clear();
        
        const username = document.getElementById('username').value.trim();
        const email = document.getElementById('email').value.trim();
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        const adminSecret = document.getElementById('adminSecret').value.trim();
        
        // 表单验证
        if (!username) {
            showCenterModal('请输入用户名');
            return;
        }
        if (username.length < 3) {
            showCenterModal('用户名至少需要3个字符');
            return;
        }
        if (!email) {
            showCenterModal('请输入邮箱');
            return;
        }
        // 简单的邮箱格式验证
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            showCenterModal('请输入有效的邮箱地址');
            return;
        }
        if (!password) {
            showCenterModal('请输入密码');
            return;
        }
        if (password.length < 6) {
            showCenterModal('密码至少需要6个字符');
            return;
        }
        if (password !== confirmPassword) {
            showCenterModal('两次输入的密码不一致');
            return;
        }
        // 管理员密文前端校验
        if (adminSecret) {
            if (adminSecret !== 'https123') {
                showCenterModal('管理员密文不正确！请重新输入或成为普通用户。');
                return;
            }
        }
        // 发送注册请求到后端
        fetch('http://localhost:3000/api/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                username: username,
                password: password,
                email: email,
                adminSecret: adminSecret
            })
        })
        .then(res => res.json())
        .then(data => {
            let successMsg = '注册成功！请使用新账号登录。';
            if (adminSecret && adminSecret === 'https123') {
                successMsg = '恭喜您注册为管理员！请使用新账号登录。';
            }
            if (data.message === '注册成功') {
                showCenterModal(successMsg, function() {
                    window.location.href = 'login.html';
                });
            } else if (data.token) {
                // 若注册后自动登录，保存token到sessionStorage
                sessionStorage.setItem('token', data.token);
            } else {
                showCenterModal(data.error || '注册失败');
            }
        })
        .catch(err => {
            showCenterModal('注册请求失败');
            console.error(err);
        });
    });
    
    // 实时密码确认验证
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirmPassword');
    
    function validatePassword() {
        const password = passwordInput.value;
        const confirmPassword = confirmPasswordInput.value;
        
        if (confirmPassword && password !== confirmPassword) {
            confirmPasswordInput.setCustomValidity('密码不匹配');
        } else {
            confirmPasswordInput.setCustomValidity('');
        }
    }
    
    passwordInput.addEventListener('input', validatePassword);
    confirmPasswordInput.addEventListener('input', validatePassword);
}); 

// 屏幕中心弹窗
function showCenterModal(message, callback) {
    let modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.left = '0';
    modal.style.top = '0';
    modal.style.width = '100vw';
    modal.style.height = '100vh';
    modal.style.background = 'rgba(0,0,0,0.18)';
    modal.style.display = 'flex';
    modal.style.alignItems = 'center';
    modal.style.justifyContent = 'center';
    modal.style.zIndex = '9999';
    modal.innerHTML = `<div style=\"background:#fff;border-radius:12px;box-shadow:0 4px 24px #0002;padding:32px 36px;min-width:320px;text-align:center;\">
        <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
        <div style='font-size:16px;margin-bottom:24px;'>${message}</div>
        <button id='centerModalBtn' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>确定</button>
    </div>`;
    document.body.appendChild(modal);
    document.getElementById('centerModalBtn').onclick = function() {
        document.body.removeChild(modal);
        if (callback) callback();
    };
} 